package com.lhf.fvssystem.dao.impl;

import com.lhf.fvssystem.dao.TableDao;
import com.lhf.fvsgenerator.entity.Column;
import com.lhf.fvsgenerator.entity.Table;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * <p></p>
 *
 * @author lhf
 * @since 2020/10/24 14:22
 */
@Repository
public class TableDaoImpl implements TableDao {


    @Resource
    private DataSource dataSource;

    @Override
    public Table tables(String tableName) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Table table = null;
        try {
            connection = dataSource.getConnection();
            String databaseName = connection.getCatalog();
            String sql = "select  table_schema,table_name,column_name,data_type,column_key,column_comment  from information_schema.COLUMNS where TABLE_SCHEMA='" + databaseName + "' AND table_name='" + tableName + "'";
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();


            table = new Table(databaseName, tableName);

            List<Column> columns = new LinkedList<>();
            while (rs.next()) {
                Column column = new Column();
                column.setColumnName(rs.getString(3));
                column.setDataType(rs.getString(4));
                column.setColumnComment(rs.getString(5));
                String key = rs.getString(6);
                if ("PRI".equalsIgnoreCase(key)) {
                    column.setColumnKey(true);
                }
            }
            table.setColumns(columns);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return table;
    }
}
